package com.kgc.scd.service.impl;

import com.kgc.scd.bean.ShopGoods;
import com.kgc.scd.bean.ShopSendMessage;
import com.kgc.scd.constant.SendMessageMQConstant;
import com.kgc.scd.mapper.ShopGoodsMapper;
import com.kgc.scd.mapper.ShopSendMessageMapper;
import com.kgc.scd.service.SendMessageService;
import com.kgc.scd.util.RedisUtils;
import com.kgc.scd.util.SnowUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created On : 2022/11/17 0017.
 * <p>
 * Author : shiguangchuan
 * <p>
 * Description: 到货提醒业务接口实现类
 */
@Service
public class SendMessageServiceImpl implements SendMessageService {

    @Autowired
    private ShopGoodsMapper shopGoodsMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ShopSendMessageMapper shopSendMessageMapper;

    @Autowired
    private SnowUtil snowUtil;

    @Override
    public boolean needSendMessageGoods(String phoneNum, String goodsId) {

        // 查询需要进行补仓提醒的商品详情并封装到实体上
        ShopGoods shopGoods = shopGoodsMapper.selectById(goodsId);

        // 判断该商品库存是否为空，能不能进行加货提醒
        if (shopGoods.getGoodsNumber() == 0){
            // 如果库存不足可以登记加仓提醒
            redisTemplate.opsForZSet().add("NeedSendMessage" + ":" + goodsId,phoneNum,0);

            // redisUtils.lSet(goodsId,phoneNum);

            // TODO 可以将数据放入数据库保存
            // 封装消息提醒实体类
            ShopSendMessage shopSendMessage = new ShopSendMessage();
            shopSendMessage.setId(snowUtil.snowId());
            shopSendMessage.setGoods_id(goodsId);
            shopSendMessage.setIsSend(0);
            shopSendMessage.setPhoneNum(phoneNum);
            shopSendMessage.setNeedTime(new Date());

            // 将提醒加货信息加入到数据库中
            shopSendMessageMapper.insert(shopSendMessage);

            return true;
        }

        // 该商品库存充足，不能操作加仓提醒
        return false;
    }

    @Override
    @Async
    public void addGoodsStockToSendMessage(String goodsId, Integer goodsNumber) {

        // 根据商品id查询到对应商品的信息，并将需要添加的数量加入进去
        ShopGoods shopGoods = shopGoodsMapper.selectById(goodsId);

        // 更改商品库存
        shopGoods.setGoodsNumber(shopGoods.getGoodsNumber() + goodsNumber);

        // 更新商品中的库存信息，将添加的库存数量更新到数据库中，同时发送消息队列，向需要接收加仓提醒的用户发送短信通知
        shopGoodsMapper.updateById(shopGoods);

        // 发送消息队列
        rabbitTemplate.convertAndSend(SendMessageMQConstant.SEND_MASSAGE_RESULT_EXCHANGE_KH96,SendMessageMQConstant.SEND_MASSAGE_RESULT_KH96,goodsId);


    }
}
